package com.service.imp;

import com.common.Base;
import com.common.Result;
import com.entity.AttentionTopic;
import com.entity.Topic;
import com.repository.AttentionTopicRepository;
import com.service.AttentionTopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

/**
 * @Author：Luohuiyong
 * @Description:
 * @Date: Created in 16:56 2019/1/30
 */
@Service
public class AttentionTopicServiceImp implements AttentionTopicService {

    @Autowired
    AttentionTopicRepository attentionTopicRepository;

    @Override
    public Topic findOne(int id) {
        return null;
    }

    /**
     * 新增数据
     * @param attentionTopic
     * @return
     */
    @Transactional
    @Override
    public Result create(AttentionTopic attentionTopic) {
        List<AttentionTopic> resList = attentionTopicRepository.findAllByUserId(attentionTopic.getUserId());
        for(int i = 0; i < resList.size();i++){
            if(resList.get(i).getTopicId() == attentionTopic.getTopicId()){
                return Base.error("已关注该专题");
            }
        }
        attentionTopic.setCreatedAt(new Date());
        attentionTopicRepository.save(attentionTopic);

        return Base.success();
    }

    /**
     * 根据该用户id获取所关注的专题
     * @param attentionTopic
     * @return
     */
    @Override
    public Result index(AttentionTopic attentionTopic) {

        Pageable pageable = new PageRequest(attentionTopic.getPage(),attentionTopic.getPageSize(), Sort.Direction.DESC,"createdAt");
        Page<AttentionTopic> page = attentionTopicRepository.findAllByUserId(attentionTopic.getUserId(),pageable);
        long total = attentionTopicRepository.countByUserId(attentionTopic.getUserId());
        long maxPage = total/attentionTopic.getPageSize();

        return Base.success(page.getContent(),total,maxPage);
    }
}
